package bubbleSort;

import emergent.World;

public class BubbleSortWorld extends World<Number> {

	protected int numberOfSwaps = 0;

	public BubbleSortWorld(int maxRows, int maxColumns, boolean syncMode) {
		super(maxRows, maxColumns, syncMode);
	}

	@Override
	public void populateWorld(boolean sync) {
		double max = (double) this.getMaxColumns();
		for (int i = 0; i < getMaxRows(); i++) {
			int[] vals = new int[this.getMaxColumns()];
			for (int j = 0; j < getMaxColumns(); j++) {
				int value = (int) (Math.random() * max);
				vals[j] = value;
				if (j != 0) {
					int k = 0;
					while (k < j) {
						if (value == vals[k]) {
							value = (int) (Math.random() * max);
							k = 0;
							continue;
						}
						k++;
					}
				}

				Number n;
				setNumberOfAgents(getNumberOfAgents() + 1);
				// n = new Number(getNumberOfAgents(), this.supervisor, value);
				n = new Number(getNumberOfAgents(), this.supervisor, sync, 1,
						value);
				n.setMyColumn(j);
				n.setMyRow(i);
				setAgent(i, j, n);
			}
		}

		addRule(new LookBottom());
		addRule(new LookRight());
		addDetector(new BSVisualDetector());
		addDetector(new TerminationDetection());

	}

	@Override
	public Number[][] instantiateWorld() {
		return new Number[getMaxRows()][getMaxColumns()];
	}

	@Override
	public void vitilizeWorld() {
		{
			System.out.println("starting threads...");
			for (int i = 0; i < getMaxRows(); i++) {
				for (int j = 0; j < getMaxColumns(); j++) {
					Number number = getAgent(i, j);
					number.setAgents(getAgents());
					Thread th = new Thread(number);
					th.start();
				}
			}

		}
	}

}
